<template>
  <div style="width:100vw;display:flex;justify-content: center;background:#F9F9F9">
    <div class="container" style="width:75vw">
      <!-- 导航栏 -->
      <AssignmentNavBar :homeworkId="homeworkId" :semesterId="semesterId" />
<div style="padding:20px 30px;background:white">
      <!-- 作业标题 -->
      <div class="assignment-summary">
        <p class="label">作业标题:</p>
        <div v-if="!isEditable" class="display-text">{{ assignmentTitle || '标题缺失' }}</div>
        <input
          v-model="assignmentTitle"
          v-show="isEditable"
          type="text"
          class="input-field"
        />
      </div>

      <!-- 作业内容 -->
      <div class="assignment-summary">
        <p class="label">作业内容:</p>
        <div v-if="!isEditable" class="display-text" v-html="formattedAssignmentContent"></div>
        <div v-show="isEditable">
          <div :class="['ql-toolbar', 'ql-snow']" :style="{ display: isEditable ? 'block' : 'none' }">
            <!-- Quill 工具栏内容 -->
          </div>
          <QuillEditor v-model="assignmentContent" :readOnly="!isEditable" />
        </div>
      </div>

      <!-- 附件 -->
      <div class="assignment-summary">
        <p class="label">附件:</p>
        <div v-if="!isEditable && attachmentUrl" class="attachment-link">
          <img src="@/assets/picture/file.png" alt="附件图标" class="icon" />
          <a :href="attachmentUrl" target="_blank" style="color:#2E4C91;text-decoration:none;">查看附件</a>
        </div>
        <div class="upload-button-wrapper" v-show="isEditable">
            <input type="file" style="display:none" ref="attachmentInput" @change="handleFileUpload" id="file" />
            <button type="button" @click="triggerFileUpload" class="upload-button">
              <img src="@/assets/picture/upload.png" alt="上传图标" style="width: 20px; margin-right: 8px;" />重新上传
            </button>
            <!-- Display selected file name for file upload -->
            <span v-if="selectedFileName" class="file-name">{{ selectedFileName }}</span>
          </div>
      </div>

      <!-- 参考答案 -->
      <div class="assignment-summary">
        <p class="label">参考答案:</p>
        <div v-if="!isEditable" class="display-text" v-html="referenceAnswer"></div>
        <div v-show="isEditable">
          <div :class="['ql-toolbar', 'ql-snow']" :style="{ display: isEditable ? 'block' : 'none' }">
            <!-- Quill 工具栏内容 -->
          </div>
          <QuillEditor v-model="referenceAnswer" :readOnly="!isEditable" />
        </div>
      </div>

      <!-- 答案附件 -->
      <div class="assignment-summary">
        <p class="label">标准答案:</p>
        <div v-if="!isEditable &&answerUrl" class="attachment-link">
          <img src="@/assets/picture/file.png" alt="附件图标" class="icon" />
          <a :href="answerUrl" target="_blank" style="color:#2E4C91;text-decoration:none;">查看附件</a>
        </div>
        <div class="upload-button-wrapper" v-show="isEditable">
            <input type="file" style="display:none" ref="answerFileInput" @change="handleAnswerFileUpload" id="file" />
            <button type="button" @click="triggerAnswerFileUpload" class="upload-button">
              <img src="@/assets/picture/upload.png" alt="上传图标" style="width: 20px; margin-right: 8px;" />重新上传
            </button>
            <!-- Display selected file name for file upload -->
            <span v-if="selectedAnswerFileName" class="file-name">{{ selectedAnswerFileName }}</span>
          </div>
      </div>

      <!-- 编辑和提交按钮 -->
      <button
        @click="toggleEdit"
        class="submit-button"
        style="margin:20px 0px"
      >{{ isEditable ? '提交' : '编辑' }}</button>
    </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import AssignmentNavBar from "@/components/AssignmentNavBar.vue";
import QuillEditor from "@/components/QuillEditor.vue";
import { fetchAssignmentDetails, updateAssignmentDetails } from "@/services/api";

export default {
  name: "AssignmentDetail",
  components: { AssignmentNavBar, QuillEditor },
  props: {
    homeworkId: {
      type: [String, Number],
      required: true
    },
    semesterId: {
      type: [String, Number],
      required: true
    }
  },
  setup(props) {
    const assignmentTitle = ref("");
    const assignmentContent = ref("");
    const formattedAssignmentContent = ref(""); 
    const attachmentUrl = ref("");
    const referenceAnswer = ref("");
    const answerUrl = ref("");
    const isEditable = ref(false);
    const selectedFile = ref(null);
    const selectedAnswerFile = ref(null);
    const selectedFileName = ref("");
    const selectedAnswerFileName = ref("");

    const getAssignmentDetails = async () => {
      try {
        const response = await fetchAssignmentDetails(props.homeworkId);
        if (response && response.data && response.data.status === 1 && response.data.data) {
          const data = response.data.data;
          assignmentTitle.value = data.hmk_title || "标题缺失";
          assignmentContent.value = data.hmk_content || "内容缺失";
          formattedAssignmentContent.value = decodeHtml(data.hmk_content);
          attachmentUrl.value = data.attachment_url || "";
          referenceAnswer.value = data.standard_answer || "答案缺失";
          answerUrl.value = data.answer_url || "";
        } else {
          const errorMessage = response.data?.msg || "未知错误";
          console.error("API 返回数据结构不符合预期:", response);
          ElMessage.error(`加载作业详情失败: ${errorMessage}`);
        }
      } catch (error) {
        console.error("获取作业详情请求失败:", error);
        ElMessage.error("加载作业详情失败，请检查网络或联系管理员。");
      }
    };

    const decodeHtml = (html) => {
      const txt = document.createElement("textarea");
      txt.innerHTML = html;
      return txt.value;
    };

    const toggleEdit = () => {
      if (isEditable.value) {
        submitAssignment();
      }
      isEditable.value = !isEditable.value;
    };

    const handleFileUpload = (event) => {
      selectedFile.value = event.target.files[0];
      selectedFileName.value = selectedFile.value.name; // Update selected file name
    };

    const handleAnswerFileUpload = (event) => {
      selectedAnswerFile.value = event.target.files[0];
      selectedAnswerFileName.value = selectedAnswerFile.value.name; // Update selected answer file name
    };

    const triggerFileUpload = () => {
      document.getElementById('file').click();
    };

    const triggerAnswerFileUpload = () => {
      document.getElementById('answerFile').click();
    };

    const submitAssignment = async () => {
      const formData = new FormData();
      formData.append("homework_id", props.homeworkId);
      formData.append("hmk_title", assignmentTitle.value);
      formData.append("hmk_content", assignmentContent.value);
      formData.append("standard_answer", referenceAnswer.value);

      if (selectedFile.value) {
        formData.append("file", selectedFile.value);
      }
      if (selectedAnswerFile.value) {
        formData.append("ans_file", selectedAnswerFile.value);
      }

      try {
        const response = await updateAssignmentDetails(formData);
        if (response.data.status === 1) {
         ElMessage.success("作业更新成功");
          getAssignmentDetails(); 
        } else {
          ElMessage.error("更新作业失败");
        }
      } catch (error) {
        console.error("提交作业失败:", error);
        ElMessage.error("提交作业失败，请检查网络或稍后重试。");
      }
    };

    onMounted(getAssignmentDetails);

    return {
      assignmentTitle,
      assignmentContent,
      formattedAssignmentContent,
      attachmentUrl,
      referenceAnswer,
      answerUrl,
      isEditable,
      selectedFile,
      selectedAnswerFile,
      selectedFileName,
      selectedAnswerFileName,
      toggleEdit,
      handleFileUpload,
      handleAnswerFileUpload,
      submitAssignment,
      triggerFileUpload,
      triggerAnswerFileUpload,
    };
  }
};
</script>

<style scoped>
.container {
  width: 100vw;
  background: #f9f9f9;
  min-height: 100vh;
  padding: 20px;
  padding-top: 0px;
}

.assignment-summary {
  background-color: #ffffff;
  padding: 20px 0px;
  border-bottom: 1px solid rgb(237, 237, 237);
  position: relative;
}

.label {
  font-weight: bold;
  color: #333333;
  margin-bottom: 8px;
}

.display-text {
  color: #666666;
  font-size: 14px;
  line-height: 1.5;
}

.input-field {
  width: 100%;
  padding: 10px;
  border: 1px solid #cccccc;
  border-radius: 5px;
  margin-top: 5px;
  font-size: 14px;
}

.attachment-link {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
}

.icon {
  width: 20px;
  height: 20px;
}

.submit-button {
  background-color: #244382;
  color: #ffffff;
  padding: 10px 40px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.submit-button:hover {
  background-color: #3e66b0;
}

.upload-button-wrapper {
  display: flex;
  align-items: center;
}
.upload-button {
  background-color: white;
  color: #333;
  padding: 6px 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.upload-button:hover {
  background-color: #d8d8d8;
}

.file-name {
  margin-left: 10px;
  font-size: 14px;
  color: #666;
}
</style>
